package wty;

import org.mindrot.jbcrypt.BCrypt;
import wty.Bee.User;
import wty.Bee.UserDao;
import org.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/wty/update")
public class UpdateUserServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入post更新");

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        //判断 HTTP 请求是否采用了multipart/form-data格式
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.getWriter().write("{\"error\":\"Invalid request format\"}");
            return;
        }

        try {
            //返回一个FileItem对象列表，每个FileItem代表表单中的一个字段
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);


            Map<String, String> formFields = new HashMap<>();
            byte[] avatarData = null;

            for (FileItem item : items) {
                if (item.isFormField()) {
                    formFields.put(item.getFieldName(), item.getString("UTF-8"));
                } else if ("avatar".equals(item.getFieldName()) && !item.getName().isEmpty()) {
                    try (InputStream fileStream = item.getInputStream();
                         ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = fileStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                        //头像数据
                        avatarData = outputStream.toByteArray();
                    }
                }
            }

            // 创建User对象
            User user = new User();
            user.setUserid(formFields.get("userId"));

            // 设置基本属性
            String username = formFields.get("username");
            String password = formFields.get("password");
            String province = formFields.get("province");
            String city = formFields.get("city");
            String email = formFields.get("email");
            String phone = formFields.get("phone");
            String gender = formFields.get("gender");
            //需要转换类型
            String birthdayStr = formFields.get("birthday");
            Date birthday = null;
            if (birthdayStr != null && !birthdayStr.isEmpty()) {
                try {
                    // 指定日期格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    birthday = sdf.parse(birthdayStr);
                } catch (ParseException e) {
                    // 处理日期格式错误
                    response.getWriter().write("{\"error\":\"Invalid birthday format, should be yyyy-MM-dd\"}");
                    return;
                }
            }
            if (birthday != null) user.setBirthday(birthday);


            if (username != null) user.setUsername(username);
            //加密存储
            if (password != null) user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
            if (province != null) user.setProvince(province);
            if (city != null) user.setCity(city);
            if (email != null) user.setEmail(email);
            if (phone != null) user.setPhone(phone);
            if (gender != null) user.setGender(gender);

            // 设置头像二进制数据
            user.setAvatar(avatarData);

            user.setRole("user");


            // 插入数据库
            UserDao userDao = new UserDao();
            userDao.update(user);

            response.getWriter().write("{\"success\":\"register success\"}");

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"error\":\"Registration failed: " + e.getMessage() + "\"}");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("收到GET请求，转发到POST处理");
        doPost(req, resp);
    }
}